if (files.cwd().endsWith("脚本")) {
  let _require = require;
  require = function (path) {
    if (path.startsWith("./")) {
      path = path.replace("./", "");
    }
    path = files.cwd() + "/gdt_hb/" + path;
    return _require(path);
  }
}

auto.waitFor();
var utils = require("./utils.js");
var storage = storages.create("xiangxiangyuedu");
var time = random(2000, 3000)

function launchAppEnhance(app_name) {
  let thread = threads.start(function () {
    toastLog("检查是否有打开权限!")
    while (true) {
      var allow = text("允许").findOne(5000)
      if (allow) {
        sleep(1000)
        toastLog("发现允许授权!")
        allow.click()
        sleep(1000)
        thread.interrupt()
        break
      }
    }
  })
  sleep(1000)
  var result = launchApp(app_name)
  sleep(3000)
  thread.interrupt()
  return result
}

// 点击控件坐标，控件的clickbale为false的时候
function 点击控件(x) {
  var weight = x.bounds()
  click(weight.centerX(), weight.centerY())
}

function task() {
  var 我的 = text('我的').findOne(20000)
  if (我的) {
    var BK = text('BK').findOne(5000)
    if (BK) {
      BK.parent().parent().click()
      utils.updateAppProgress(20);
      sleep(time)
      var 我的任务 = text('我的任务').findOne(5000)
      if (我的任务) {
        点击控件(我的任务)
        sleep(5000)
        var index = 0
        while (index < 3) {
          var 去完成 = text('去完成').findOne(1000)
          if (去完成) {
            var finalActivity = currentActivity()
            去完成.click()
            sleep(5000)
            var 提示 = text('提示').findOne(1000)
            if (提示) {
              toastLog('已经完成任务')
              sleep(time)
              break
            }
            var 我的任务 = text('我的任务').findOne(1000)
            if (!我的任务) {
              toastLog('当前是广告界面')
              utils.waitAdvert(finalActivity);
              sleep(time)
            }
          }
          index++
          utils.updateAppProgress(index * 30);
        }
      }
    }
  }
}

function main() {
  let open_app = launchAppEnhance("多彩世界");
  if (open_app) {
    task()
  }
  else {
    toastLog("多彩世界打开失败，请确认是否安装并授权打开!");
  }
}

try {
  main();
  utils.updateAppProgress(100);
} catch (error) {
  toastLog(error);
}

storage.put("script_running_status", "end");
